/************************************************
 * Copyright (c) 2007 ~ 2009, 
 * All rights reserved.
 * Version   : 1.0
 * Author    : lengsh@alibaba-inc.com 
 * Date      : 2009.1.2
 ************************************************/

#ifndef _GONGFU_PANDA_THREAD_H_
#define _GONGFU_PANDA_THREAD_H_

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <iostream>
#include "Defines.h"

using namespace std;

class Threads
{
	public:
		LIBEVENT_THREAD *threads;
		/* Lock for connection freelist */
		pthread_mutex_t conn_lock;
		/* Free list of CQ_ITEM structs */
		CQ_ITEM *cqi_freelist;
		pthread_mutex_t cqi_freelist_lock;
		/* Number of threads that have finished setting themselves up.  */
		int init_count;
		/* Which thread we assigned a connection to most recently. */
		int last_thread;
		pthread_mutex_t init_lock;
		pthread_cond_t init_cond;
	public:
		Threads(){  
			init_count = 0;
			last_thread = -1;
			cqi_freelist = NULL;
			threads = NULL;
		}
		~Threads(){}
	public:
		void cq_init(CQ *cq) ;
		CQ_ITEM *cq_pop(CQ *cq) ;
		CQ_ITEM *cq_peek(CQ *cq) ;
		void cq_push(CQ *cq, CQ_ITEM *item) ;
		CQ_ITEM *cqi_new(); 
		void cqi_free(CQ_ITEM *item);
		void create_worker(void *(*func)(void *), void *arg);
		conn *conn_from_freelist() ;
		bool conn_add_to_freelist(conn *c);
		void setup_thread(LIBEVENT_THREAD *me);
		void dispatch_conn_new(int sfd, int init_state, int event_flags, int read_buffer_size, int is_udp);
		int is_listen_thread();
		void run_deferred_deletes();
		void thread_init(int nthreads, struct event_base *main_base);
		int InitCountIncrease();
};

#endif
